package com.sora.serializer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sora.entity.RpcRequest;
import com.sora.enumeration.SerializerCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @Classname: JsonSerializer
 * @Description:
 * @Author: Stonffe
 * @Date: 2023/4/30 23:25
 */
public class JsonSerializer implements CommonSerializer{
    private static final Logger logger = LoggerFactory.getLogger(JsonSerializer.class);
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public byte[] serialize(Object obj) {
        try {
            return objectMapper.writeValueAsBytes(obj);
        } catch (JsonProcessingException e) {
            logger.error("序列化时有错误发生：{}", e.getMessage());
            return null;
        }
    }

    @Override
    public Object deserialize(byte[] bytes, Class<?> clazz) {
        try {
            Object value = objectMapper.readValue(bytes, clazz);
            if (value instanceof RpcRequest) {
                value = handleRequest(value);
            }
            return value;
        } catch (IOException e) {
            logger.error("反序列化时有错误发生：{}", e.getMessage());
            return null;
        }
    }
    private Object handleRequest(Object obj) throws IOException {
        RpcRequest request = (RpcRequest) obj;
        for (int i = 0; i < request.getParamType().length; i++) {
            Class<?> clazz = request.getParamType()[i];
            if (!clazz.isAssignableFrom(request.getParameters()[i].getClass())) {
                byte[] bytes = objectMapper.writeValueAsBytes(request.getParameters()[i]);
                request.getParameters()[i] = objectMapper.readValue(bytes, clazz);
            }
        }
        return request;
    }
    @Override
    public int getCode() {
        return SerializerCode.valueOf("JSON").getCode();
    }
}
